//
// Created by zhupi on 2024/10/27.
//

#ifndef DEMO2_PYTHON_TEST_H
#define DEMO2_PYTHON_TEST_H


#include <QApplication>
#include <QPlainTextEdit>
#include <QKeyEvent>
#include <QMenu>
#include <QClipboard>
#include <QVBoxLayout>
#include <QWidget>
#include <QTextCursor>
#include <QTextBlock>
#include <QDebug>
#include <QMimeData>
// qDebug() <<"data is :" << line;

#include <QTimer>
class CommandLineWidget : public QPlainTextEdit {
Q_OBJECT

public:
    CommandLineWidget(QWidget *parent = nullptr) : QPlainTextEdit(parent), isPasting_(false), pastedLineCount_(0) {
        setPlaceholderText("Type your command here...");
        setContextMenuPolicy(Qt::CustomContextMenu);

        connect(this, &QPlainTextEdit::customContextMenuRequested, this, &CommandLineWidget::ShowContextMenu);
        InsertPrompt();
    }

signals:
    void SendLineDataSg(const QString &data);

protected:
    void keyPressEvent(QKeyEvent *event) override {
        // 捕获 Ctrl+Z（撤销）操作
        if (event->key() == Qt::Key_Z && event->modifiers() == Qt::ControlModifier) {
            // 执行撤销操作
            QPlainTextEdit::undo();
            // 将光标移动到文本末尾
            moveCursor(QTextCursor::End);
            return;
        }

        if (event->key() == Qt::Key_Backspace) {
            if (textCursor().positionInBlock() > PromptLength()) {
                QPlainTextEdit::keyPressEvent(event);
            }
        } else if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
            ProcessAndSendLines();
            InsertPrompt();
        } else {
            QPlainTextEdit::keyPressEvent(event);
        }
    }

    void insertFromMimeData(const QMimeData *source) override {
        // 标记为粘贴操作，并记录粘贴的行数
        isPasting_ = true;

        if (source->hasText()) {
            QString pastedText = source->text();
            QStringList lines = pastedText.split('\n', Qt::SkipEmptyParts);
            pastedLineCount_ = lines.size(); // 记录粘贴的行数

            for (const QString &line : lines) {
                appendPlainText(">>>: " + line);
            }
            moveCursor(QTextCursor::End); // 确保光标在最后
        }
    }

private:
    int PromptLength() const {
        return 4; // ">>>: " 的长度
    }

    void InsertPrompt() {
        moveCursor(QTextCursor::End);
        insertPlainText("\n>>>: ");  // 先插入换行，再插入提示符
    }

    void ProcessAndSendLines() {
        if (isPasting_) {
            // 获取最后粘贴的几行内容
            QString currentText = toPlainText();
            QStringList lines = currentText.split('\n', Qt::SkipEmptyParts);

            // 仅发送最后粘贴的几行内容
            int startLine = lines.size() - pastedLineCount_;
            for (int i = startLine; i < lines.size(); ++i) {
                QString line = lines[i].mid(PromptLength()).trimmed();  // 去掉 ">>>: " 提示符并发送纯文本
                if (!line.isEmpty()) {
                    QTimer::singleShot((i - startLine) * 100, [this, line]() {
                        emit SendLineDataSg(line);
                        qDebug() <<"data is :" << line;
                    });
                }
            }

            // 重置粘贴标志和行计数
            isPasting_ = false;
            pastedLineCount_ = 0;
        } else {
            // 获取当前行内容并发送
            QString currentLine = textCursor().block().text().mid(PromptLength()).trimmed();
            if (!currentLine.isEmpty()) {
                emit SendLineDataSg(currentLine);
                qDebug() << "====================" << currentLine;
            }
        }

        // 移动光标到最后，插入新的提示符而不删除已有内容
        moveCursor(QTextCursor::End);
    }

    void ShowContextMenu(const QPoint &pos) {
        QMenu contextMenu;

        QAction *clearAction = contextMenu.addAction("清除当前内容");
        QAction *copyAllAction = contextMenu.addAction("拷贝当前窗口");

        connect(clearAction, &QAction::triggered, this, &CommandLineWidget::ClearContent);
        connect(copyAllAction, &QAction::triggered, this, &CommandLineWidget::CopyAllContent);

        contextMenu.exec(mapToGlobal(pos));
    }

    void ClearContent() {
        clear();
        InsertPrompt();
    }

    void CopyAllContent() {
        QStringList lines = toPlainText().split('\n');
        QStringList pureLines;
        for (const QString &line : lines) {
            if (line.startsWith(">>>: ")) {
                pureLines << line.mid(PromptLength()).trimmed();  // 去掉 ">>>: "
            } else {
                pureLines << line.trimmed();
            }
        }
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(pureLines.join("\n"));
    }

    bool isPasting_;         // 标志位：用于区分粘贴操作和正常输入
    int pastedLineCount_;    // 粘贴的行数
};


#endif //DEMO2_PYTHON_TEST_H
